<template>
  <el-dropdown trigger="click">
    <div class="avatar flx-center">
      <img
        src="https://ts4.cn.mm.bing.net/th?id=ODLS.d87cb855-ded8-4732-827b-ad001f2fa9b3&w=16&h=16&o=6&pid=1.2"
        alt="avatar"
      />
      <span class="nick sle">这是昵称这是昵称</span>
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="openDialog('infoRef')">
          <el-icon><User /></el-icon>{{ $t('header.personalData') }}
        </el-dropdown-item>
        <el-dropdown-item @click="openDialog('passwordRef')">
          <el-icon><Edit /></el-icon>{{ $t('header.changePassword') }}
        </el-dropdown-item>
        <el-dropdown-item @click="logout" divided>
          <el-icon><SwitchButton /></el-icon>{{ $t('header.logout') }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <!-- infoDialog -->
  <InfoDialog ref="infoRef"></InfoDialog>
  <!-- passwordDialog -->
  <PasswordDialog ref="passwordRef"></PasswordDialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { GlobalStore } from '@/store'
import { LOGIN_URL } from '@/config/config'
import { logoutApi } from '@/api/modules/login'
import InfoDialog from './InfoDialog.vue'
import PasswordDialog from './PasswordDialog.vue'

const router = useRouter()
const globalStore = GlobalStore()

/**
 * @description: 退出登录
 * @return {*}
 */
const logout = () => {
  ElMessageBox.confirm('您是否确认退出登录?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 1.调用退出登录接口
    await logoutApi()
    // 2.清除 Token
    globalStore.setToken('')
    // 3.重定向到登陆页
    router.replace(LOGIN_URL)
    ElMessage.success('退出登录成功！')
  })
}

interface DialogExpose {
  openDialog: () => void
}
const infoRef = ref<null | DialogExpose>(null)
const passwordRef = ref<null | DialogExpose>(null)
// 打开修改密码和个人信息弹窗
const openDialog = (refName: string) => {
  if (refName === 'infoRef') infoRef.value?.openDialog()
  else passwordRef.value?.openDialog()
}
</script>

<style scoped lang="scss">
.avatar {
  width: 140px;
  height: 40px;
  border-radius: 3px;
  background: #ffffff;
  cursor: pointer;
  img {
    width: 25px;
    height: 25px;
    border-radius: 50%;
  }
  .nick {
    flex-shrink: 0;
    margin-left: 5px;
    width: 70px;
  }
}
</style>
